import { Controller, Get, HttpException, HttpStatus, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Authorities } from 'src/decorators/authorities.decorator';
import { AuthoritiesGuard } from 'src/guards/authorities.guard';
import { LantUtil } from '../../../../utils/lant.util';
import { UuidNameResDto } from '../../../common/dtos/uuid-name.res.dto';
import { LogAppender } from '../../../log/constants/log.constant';
import { LogService } from '../../../log/services/log.service';
import { Guard } from '../../constants/guard.constant';
import { GuardService } from '../../services/guard.service';
const pinyin = require('pinyin');

@ApiBearerAuth()
@ApiTags('guards')
@Controller('admin/guards')
export class GuardAdminController {
  constructor(private readonly guardService: GuardService, private readonly logService: LogService, private readonly lantUtil: LantUtil) {}

  @ApiOperation({ summary: '获取权限列表' })
  @ApiOkResponse({ description: '权限列表', type: UuidNameResDto, isArray: true })
  @Authorities(Guard.GuardView)
  @UseGuards(AuthGuard(), AuthoritiesGuard)
  @Get()
  async getAll(): Promise<UuidNameResDto[]> {
    try {
      const guardList = await this.guardService.find();
      const sortedGuardList = guardList.sort(function compareFunction(current, next) {
        return pinyin.compare(current.name, next.name);
      });

      return sortedGuardList.map(guard => {
        return {
          uuid: guard.uuid,
          name: guard.displayName
        };
      });
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.error(LogAppender.guard, `Cannot get guard list , the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
